package edu.kaist.cs408.pof.backend.dao;

import com.google.code.morphia.Key;
import com.google.code.morphia.query.UpdateOperations;
import edu.kaist.cs408.pof.common.model.DishVo;
import edu.kaist.cs408.pof.common.model.RestaurantVo;
import edu.kaist.cs408.pof.common.model.TalkVo;
import edu.kaist.cs408.pof.common.model.UserVo;
import org.bson.types.ObjectId;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: duyleekun
 * Date: 5/12/12
 * Time: 4:55 AM
 * To change this template use File | Settings | File Templates.
 */

@Configuration
public class TalkDaoImpl extends DaoBase {
	public List<TalkVo> getAll(int offset, int limit) {
		return datastore.find(TalkVo.class).limit(limit).offset(offset).asList();
	}

	public List<TalkVo> getAboutDish(ObjectId dish, int offset, int limit) {
		return datastore.find(TalkVo.class).field("dish").equal(new Key(DishVo.class, dish)).offset(offset).limit(limit).asList();
	}

	public List<TalkVo> getAboutRestaurant(ObjectId restaurant, int offset, int limit) {
		return datastore.find(TalkVo.class).field("restaurant").equal(new Key(RestaurantVo.class, restaurant)).offset(offset).limit(limit).asList();
	}

	public TalkVo createTalk(TalkVo aTalk) {
		datastore.save(aTalk);
		return aTalk;
	}

	public TalkVo setTalk(ObjectId aTalk, ObjectId aUser, ObjectId aRestaurant, ObjectId aDish) {
		UpdateOperations<TalkVo> upDateOp = datastore.createUpdateOperations(TalkVo.class);
		if (aUser != null)
			upDateOp = upDateOp.set("user", new Key(UserVo.class, aUser));
		if (aRestaurant != null)
			upDateOp = upDateOp.set("restaurant", new Key(RestaurantVo.class, aRestaurant));
		if (aDish != null)
			upDateOp = upDateOp.set("dish", new Key(DishVo.class, aDish));
		return datastore.findAndModify(datastore.find(TalkVo.class, "_id", aTalk), upDateOp);
	}

}
